package vip.xiaonuo.smzq.modular.kcl.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.netty.util.internal.ObjectUtil;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.smzq.core.tools.excel.ExcelExporter;
import vip.xiaonuo.smzq.modular.deom.ToolData;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb01Zh;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb06Kc;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb08Xzqh;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb01ZhMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb06KcMapper;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb08XzqhMapper;
import vip.xiaonuo.smzq.modular.kcl.entity.Ks;
import vip.xiaonuo.smzq.modular.kcl.entity.Sjyj;
import vip.xiaonuo.smzq.modular.kcl.entity.vo.EarlyWarningTypeCount;
import vip.xiaonuo.smzq.modular.kcl.mapper.KsMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.SjyjMapper;
import vip.xiaonuo.smzq.modular.kcl.mapper.ZyclMapper;
import vip.xiaonuo.smzq.modular.kcl.service.ISjyjService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.smzq.modular.user.entity.User;
import vip.xiaonuo.smzq.modular.user.mapper.OrgMapper;
import vip.xiaonuo.smzq.modular.user.mapper.UserMapper;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

/**
 * 矿山数据预警 服务实现类
 *
 * @author sqq
 * @since 2024-06-04
 */
@Service
public class SjyjServiceImpl extends ServiceImpl<SjyjMapper, Sjyj> implements ISjyjService {

    @Resource
    private SjyjMapper sjyjMapper;

    @Resource
    private UserMapper userMapper;//用户

    @Resource
    private ZyclMapper zyclMapper;//资源储量

    @Resource
    private KsMapper ksMapper; //矿山

    @Resource
    private Cb08XzqhMapper cb08XzqhMapper;//行政区划

    @Resource
    private Cb01ZhMapper cb01ZhMapper;//综合字典类型

    @Resource
    private Cb06KcMapper cb06KcMapper; //矿产
    @Resource
    private OrgMapper orgMapper;//级别部省市县填报

    @Override
    public Page<Sjyj> page(Sjyj sjyj) {
        QueryWrapper<Sjyj> queryWrapper = new QueryWrapper<>();
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public Page<Sjyj> page(long current, long size, Integer nd, String xzqh, Integer sjyjlxbm,Integer djflbh,String kqbh) {
        Page<Sjyj> page = new Page<>(current, size);
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        LambdaQueryWrapper<Sjyj> queryWrapper = new LambdaQueryWrapper<>();

        if (nd==null){
            String time = DateUtil.format(new Date(), "YYYY");
            nd=Integer.parseInt(time);
        }
        queryWrapper.eq(Sjyj::getNd, nd);

        if (xzqh == null){
            if (user.getOrgId().equals("-1")||user.getOrgId().length()>8){
                xzqh="130000";
            }else{
                xzqh= user.getOrgId();
            }
        }
        xzqh = xzqh.replaceAll("0+$", "");
        queryWrapper.likeRight(Sjyj::getXzqhdm, xzqh);
        if (sjyjlxbm != null){
            queryWrapper.eq(Sjyj::getSjyjlxbm, sjyjlxbm);
        }
        if (djflbh != null){
            queryWrapper.eq(Sjyj::getDjflbh, djflbh);
        }
        if (kqbh != null){
            queryWrapper.eq(Sjyj::getKqbh, kqbh);
        }

        queryWrapper.orderByDesc(Sjyj::getNd);
        queryWrapper.orderByAsc(Sjyj::getKqbh, Sjyj::getDjflbh);
        page= sjyjMapper.selectPage(page, queryWrapper);
        return page;
    }

    /**
     * 矿山数据预警-导出Excel
     * @param nd
     * @param xzqh
     * @param sjyjlxbm
     * @param djflbh
     * @param kqbh
     * @param response
     */
    @Override
    public void exportKsyj(Integer nd, String xzqh, Integer sjyjlxbm, Integer djflbh, String kqbh, HttpServletResponse response) {
        // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        LambdaQueryWrapper<Sjyj> queryWrapper = new LambdaQueryWrapper<>();

        if (nd==null){
            String time = DateUtil.format(new Date(), "YYYY");
            nd=Integer.parseInt(time);
        }
        queryWrapper.eq(Sjyj::getNd, nd);
        if (xzqh == null){
            if (user.getOrgId().equals("-1")||user.getOrgId().length()>8){
                xzqh="130000";
            }else{
                xzqh= user.getOrgId();
            }
        }
        xzqh = xzqh.replaceAll("0+$", "");
        queryWrapper.likeRight(Sjyj::getXzqhdm, xzqh);
        if (sjyjlxbm != null){
            queryWrapper.eq(Sjyj::getSjyjlxbm, sjyjlxbm);
        }
        if (djflbh != null){
            queryWrapper.eq(Sjyj::getDjflbh, djflbh);
        }
        if (kqbh != null){
            queryWrapper.eq(Sjyj::getKqbh, kqbh);
        }

        queryWrapper.orderByDesc(Sjyj::getNd);
        queryWrapper.orderByAsc(Sjyj::getKqbh, Sjyj::getDjflbh);

        List<Sjyj> list = sjyjMapper.selectList(queryWrapper);

        try {
            ExcelExporter.exportKsyj(list, response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void reservesDataEarlywarning(String kqbh, Integer nd, Integer djflbh) {
        QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
        queryWrapperKs.eq("kqbh", kqbh);
        queryWrapperKs.eq("nd", nd);
        queryWrapperKs.eq("djflbh", djflbh);
        Ks ks = ksMapper.selectOne(queryWrapperKs);

        String xzqhmc="";

        if (ks.getXzqdm()!=null){
            QueryWrapper<Cb08Xzqh> queryWrapperXzqh = new QueryWrapper<>();
            queryWrapperXzqh.eq("dm", ks.getXzqdm());
            Cb08Xzqh b08Xzqh=cb08XzqhMapper.selectOne(queryWrapperXzqh);
            xzqhmc=b08Xzqh.getMc();
        }

        //避免多次提交年报此处做删除记录
        delectSjyj(nd,djflbh,kqbh,null);

        QueryWrapper<Cb01Zh> queryWrapperZycl = new QueryWrapper<>();
        QueryWrapper<Cb01Zh> queryWrapperZycl1 = new QueryWrapper<>();
        QueryWrapper<Cb01Zh> queryWrapperZycl2 = new QueryWrapper<>();
        QueryWrapper<Cb01Zh> queryWrapperZycl3 = new QueryWrapper<>();

      List<Integer> kcList =  zyclMapper.getKcList(kqbh,djflbh,nd);
      for (Integer kc : kcList){
          //矿产名称
          QueryWrapper<Cb06Kc> queryWrapperKc = new QueryWrapper<>();
          queryWrapperKc.eq("kcdm", kc);
          queryWrapperKc.last("limit 1");
          Cb06Kc cb06Kc = cb06KcMapper.selectOne(queryWrapperKc);
          Sjyj sjyj = new Sjyj();
          sjyj.setKqbh(kqbh);
          sjyj.setKcdm(kc);
          sjyj.setKcmc(cb06Kc.getKcmc());
          sjyj.setDjflbh(djflbh);
          sjyj.setKsbh(ks.getKsbh());
          sjyj.setNd(nd);
          sjyj.setXkzh(ks.getXkzh());
          sjyj.setKsmc(ks.getKsmc());
          sjyj.setKyqr(ks.getKyqr());
          sjyj.setXzqhdm(String.valueOf(ks.getXzqdm()));
          sjyj.setXzqhmc(xzqhmc);

          // |（校验今年资源量-上年度资源量）|/上年度资源量>0.5
        Double bili= sjyjMapper.getBili(kqbh,nd,djflbh,kc);

        if (bili==null||bili>0.5||-0.5>bili){ //308003
            sjyj.setPkid(UUID.randomUUID().toString());
            if (bili!=null){
                sjyj.setBhlbfb(ToolData.roundToTwoDecimals(bili * 100) +"%");

            }else{
                sjyj.setBhlbfb("∞");
            }
            sjyj.setSjyjlxbm(308003);
            queryWrapperZycl.eq("dm", 308003);
            sjyj.setSjyjlx(cb01ZhMapper.selectOne(queryWrapperZycl).getMc());
            sjyjMapper.insert(sjyj);
        }
         //|(累计查明变动量-年初累计查明量)|/年初累计查明量> 30%
          Double ljbili= sjyjMapper.getLjbili(kqbh,nd,djflbh,kc);
         if (ljbili==null||ljbili>0.3||-0.3>ljbili){
             sjyj.setPkid(UUID.randomUUID().toString());
             if (ljbili!=null){
                 sjyj.setBhlbfb(ToolData.roundToTwoDecimals(ljbili * 100) +"%");
             }else{
                 sjyj.setBhlbfb("∞");
             }
             sjyj.setSjyjlxbm(308005);
             queryWrapperZycl1.eq("dm", 308005);
             sjyj.setSjyjlx(cb01ZhMapper.selectOne(queryWrapperZycl1).getMc());
             sjyjMapper.insert(sjyj);
         }

         //生产（关闭、停产）矿山储量为0
         Double zyl=sjyjMapper.getZyl(kqbh,nd,djflbh,kc);
          if (zyl ==null||zyl==0){
              sjyj.setPkid(UUID.randomUUID().toString());
              sjyj.setSjyjlxbm(308004);
              queryWrapperZycl2.eq("dm", 308004);
              sjyj.setSjyjlx(cb01ZhMapper.selectOne(queryWrapperZycl2).getMc());
              sjyjMapper.insert(sjyj);
          }

          Double clbh=sjyjMapper.getClbh(kqbh,nd,djflbh,kc);
          if (clbh==null||clbh<0.3){
              sjyj.setPkid(UUID.randomUUID().toString());
              sjyj.setSjyjlxbm(308006);
              queryWrapperZycl3.eq("dm", 308006);
              sjyj.setSjyjlx(cb01ZhMapper.selectOne(queryWrapperZycl3).getMc());
              sjyjMapper.insert(sjyj);
          }
      }
    }

    @Override
    public EarlyWarningTypeCount getEarlyWarningTypeCount(Integer nd, String xzqh, Integer sjyjlxbm, Integer djflbh, String kqbh) {

         // 获取用户信息
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        User user = userMapper.selectById(saBaseLoginUser.getId());

        if (nd==null){
            String time = DateUtil.format(new Date(), "YYYY");
            nd=Integer.parseInt(time);
        }


        if (xzqh == null){
            if (user.getOrgId().equals("-1")||user.getOrgId().length()>8){
                xzqh="130000";
            }else{
                xzqh= user.getOrgId();
            }
        }
        xzqh = xzqh.replaceAll("0+$", "");


        MPJLambdaWrapper<Sjyj> wrapper=new MPJLambdaWrapper<>();
        wrapper.
                //"生产（关闭、停产）矿山储量为0"
                selectAs("SUM(CASE WHEN sjyjlxbm = 308004 THEN 1 ELSE 0 END)",EarlyWarningTypeCount::getKscl)
                // "今年资源量/上年度资源量>150%"
                .selectAs("SUM(CASE WHEN sjyjlxbm = 308003 THEN 1 ELSE 0 END)",EarlyWarningTypeCount::getZyl)
                //累计查明变动量/年初累计查明量 > 30%
                .selectAs("SUM(CASE WHEN sjyjlxbm = 308005 THEN 1 ELSE 0 END)",EarlyWarningTypeCount::getLjcml)
                //矿区未利用部分填报储量提示
                .selectAs("SUM(CASE WHEN sjyjlxbm = 308001 THEN 1 ELSE 0 END)",EarlyWarningTypeCount::getWlyl)
                //矿山填报储量提示
                .selectAs("SUM(CASE WHEN sjyjlxbm = 308002 THEN 1 ELSE 0 END)",EarlyWarningTypeCount::getKstb)
                //矿山填报储量提示
                .selectAs("SUM(CASE WHEN sjyjlxbm = 308006 THEN 1 ELSE 0 END)",EarlyWarningTypeCount::getKsclbh)
                .eq(Sjyj::getNd, nd)
                .likeRight(Sjyj::getXzqhdm, xzqh)
                .eq(ObjUtil.isNotEmpty(djflbh),Sjyj::getDjflbh, djflbh)
                .eq(ObjUtil.isNotEmpty(kqbh),Sjyj::getKqbh, kqbh);

     return  sjyjMapper.selectJoinOne(EarlyWarningTypeCount.class,wrapper);

    }

    /**
     * 填报任务提交之后删除填报预警
     * @param nd
     * @param djflbm
     * @param kqbh
     * @param sjyjlxbm 数据类型预警编码
     */
    @Override
    public void delectSjyj(Integer nd, Integer djflbm, String kqbh,Integer sjyjlxbm) {
        QueryWrapper<Sjyj> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("kqbh", kqbh);
        queryWrapper.eq("nd", nd);
        queryWrapper.eq("djflbh", djflbm);
        if (sjyjlxbm!=null){
            queryWrapper.eq("sjyjlxbm", sjyjlxbm);
        }
        sjyjMapper.delete(queryWrapper);
    }

    /**
     * 填报审批通过之后添加下一年度的填报预警
     * @param nd
     * @param djflbm
     * @param kqbh
     * @param sjyjlxbm
     */
    @Override
    public void addSjyj(Integer nd, Integer djflbm, String kqbh, int sjyjlxbm) {
        //避免记录产生冗余数据先执行删除
        delectSjyj(nd+1,djflbm,kqbh,sjyjlxbm);
        //矿山信息查询
        QueryWrapper<Ks> queryWrapperKs = new QueryWrapper<>();
        queryWrapperKs.eq("kqbh", kqbh);
        queryWrapperKs.eq("nd", nd);
        queryWrapperKs.eq("djflbh", djflbm);
        Ks ks = ksMapper.selectOne(queryWrapperKs);


        //行政区划
        String xzqhmc="";
        if (ks.getXzqdm()!=null){
            QueryWrapper<Cb08Xzqh> queryWrapperXzqh = new QueryWrapper<>();
            queryWrapperXzqh.eq("dm", ks.getXzqdm());
            Cb08Xzqh b08Xzqh=cb08XzqhMapper.selectOne(queryWrapperXzqh);
            xzqhmc=b08Xzqh.getMc();
        }

        Sjyj sjyj=new Sjyj();
        sjyj.setKqbh(kqbh);
        sjyj.setDjflbh(djflbm);
        sjyj.setKsbh(ks.getKsbh());
        sjyj.setNd(nd+1);
        sjyj.setXkzh(ks.getXkzh());
        sjyj.setKsmc(ks.getKsmc());
        sjyj.setKyqr(ks.getKyqr());
        sjyj.setXzqhdm(String.valueOf(ks.getXzqdm()));
        sjyj.setXzqhmc(xzqhmc);

        //预警类型以及类型名称
        sjyj.setSjyjlxbm(sjyjlxbm);
        QueryWrapper<Cb01Zh> queryWrapperZh = new QueryWrapper<>();
        queryWrapperZh.eq("dm", sjyjlxbm);
        sjyj.setSjyjlx(cb01ZhMapper.selectOne(queryWrapperZh).getMc());
        sjyjMapper.insert(sjyj);

    }

    /**
     * 同步某年的消息预警信息
     */
    @Transactional
    @Override
    public void synchronousMessageAlert(Integer nd) {

        LambdaQueryWrapper<Ks> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Ks::getNd,nd);
        queryWrapper.in(Ks::getSbbs,1,2);
        List<Ks> ksList=ksMapper.selectList(queryWrapper);

for (Ks ks:ksList){
//    try {
        reservesDataEarlywarning(ks.getKqbh(),nd,ks.getDjflbh());

        if (ks.getDjflbh() > 2000 && ks.getDjflbh() < 3000) {
           addSjyj(ks.getNd(), ks.getDjflbh(), ks.getKqbh(), 308002);
        } else {
           addSjyj(ks.getNd(), ks.getDjflbh(), ks.getKqbh(), 308001);
        }
        System.out.println("年度：" + ks.getNd() + "---矿区编号：" + ks.getKqbh() + "---登记分类编号:" + ks.getDjflbh() + "---消息预警数据同步成功");
//    }catch (Exception e){
//        System.out.println("年度：" + ks.getNd() + "---矿区编号：" + ks.getKqbh() + "---登记分类编号:" + ks.getDjflbh() + "---消息预警数据同步失败");
//    }

}











    }
}
